
with open('data/problem017.txt') as file:
    list = [pair.split() for pair in file.read().strip().split('\n')]
    dict = {}
    for num, word in list:
        dict[num] = word

def to_words(n):
    ns = str(n)
    if n <=20:
        return dict[ns]
    elif n < 100:
        if n%10 == 0:
            return dict[ns]
        else:
            return "%s%s" % (dict[ns[0]+'0'], dict[ns[1]])
    elif n < 1000:
        if n%100 == 0:
            return "%s%s" % (dict[ns[0]], dict['100'])
        else:
            return "%s%sand%s" %\
                (dict[ns[0]], dict['100'], to_words(int(ns[1:])))
    else:
        return "%s%s" % (dict['1'], dict['1000'])

print sum([len(to_words(i)) for i in range(1, 1001)])
